package com.java.lb.impl;

import com.java.lb.LoadBalance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.List;

@Component
public class RoundLoadBalance implements LoadBalance {

    @Autowired
    private DiscoveryClient discoveryClient;

    private List<ServiceInstance> instances = null;

    private int i = 0;

    // @PostConstruct 所标注的方法，会在构造器执行完毕之后，属性注入完毕以后，才执行
    @PostConstruct
    public void init() {
        instances = discoveryClient.getInstances("moon-teacher");
    }

    @Override
    public String getServerIp() {
        ServiceInstance service = instances.get(i++);
        if (i > instances.size() - 1) {
            i = 0;
        }
        return service.getUri().toString();
    }

}
